package com.sojson.project.filedepot.service.impl.thread;

import java.util.ArrayList;
import java.util.List;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import com.sojson.project.filedepot.dao.FileDepotDao;
import com.sojson.project.filedepot.entity.vo.FileDepotVo;
import com.sojson.project.filedepot.entity.vo.FileTableVo;
import com.sojson.project.filedepot.service.FileDepotService;
import com.sojson.project.filedepot.service.FileTableService;
import com.sojson.util.file.depot.FileDepotUtil;

import lombok.extern.slf4j.Slf4j;

/**
 * 文件库Service实现类
 * 
 * @author liu
 * @date 2021-05-26
 */
@Slf4j
@Service
public class FileDepotThreadImpl {

    @Lazy
    @Autowired
    private FileDepotService fileDepotService;
    @Resource
    private FileTableService fileTableService;
    @Resource
    private FileDepotDao fileDepotDao;

    /**
     * 清空旧文件
     * 
     * @return
     */
    @Async
    public void clearFile() {
        log.info("---------------手动开始清空表和字段已删除的文件----------------");
        List<Integer> arrayList = new ArrayList<>();
        List<FileTableVo> findTables = fileTableService.findTables();
        for (FileTableVo fileTable : findTables) {
            arrayList.add(fileTable.getCode());
        }

        try {
            List<FileDepotVo> pathListOther = fileDepotDao.getPathListTableNull(arrayList);
            FileDepotUtil.deleteFileList(pathListOther);
            log.info("---------------清除: " + pathListOther.size() + "个表已删除的文件----------------");
        } catch (Exception e) {
            log.error("删除表已删除的文件失败，" + e.getMessage());
        }

        List<FileDepotVo> pathList = null;
        for (FileTableVo fileTable : findTables) {
            if (fileTable.getFields().size() < 1) {
                continue;
            }
            try {
                // 获取状态为未引用的文件
                pathList = fileDepotDao.getPathListFieldNull(fileTable);
                FileDepotUtil.deleteFileList(pathList);
                log.info("---------------删除" + fileTable.getTableName() + "表: " + pathList.size()
                    + "个字段已删除的文件----------------");
            } catch (Exception e) {
                log.error(e.getMessage(), e);
                log.error("删除字段已删除的文件失败，" + e.getMessage());
                fileDepotService.clearImgMonthWarn();
            }
        }
        log.info("---------------手动清空表和字段已删除的文件结束----------------");
    }

}